import psutil
from datetime import datetime

from utils.extensions import socketio
from utils import sleep_redis
from utils.logger import get_logger, INFO

# 创建专用的推送日志记录器
pusher_logger = get_logger("system_pusher", level=INFO, daily_rotation=True)


class SystemPusher:
    """系统数据推送类，用于定时采集并推送服务器状态"""

    def __init__(self, interval=2):
        """初始化推送器

        Args:
            interval: 推送间隔，单位为秒，默认2秒
        """
        self.interval = interval
        self.is_running = False
        self.job_id = 'system_push_job'  # 使用不同的job_id
        self.device_count_job_id = 'device_count_push_job'  # 设备数量推送的job_id

    def start(self, scheduler=None):
        """启动数据推送

        Args:
            scheduler: 调度器实例，如果为None则不会自动注册任务
        """
        if not self.is_running and scheduler:
            # 启动系统状态推送
            scheduler.add_job(
                self.push_system_status,
                'interval',
                seconds=self.interval,
                id=self.job_id
            )

            # 启动设备数量推送（每分钟一次）
            scheduler.add_job(
                self.push_online_device_count,
                'interval',
                seconds=10,
                id=self.device_count_job_id
            )
            
            self.is_running = True
            pusher_logger.info(f"数据推送已启动，系统状态推送间隔: {self.interval}秒，设备数量推送间隔: 1分钟")

    def stop(self, scheduler=None):
        """停止数据推送"""
        if self.is_running and scheduler:
            scheduler.remove_job(self.job_id)
            scheduler.remove_job(self.device_count_job_id)
            self.is_running = False
            pusher_logger.info("数据推送已停止")

    def push_system_status(self):
        """采集系统数据并推送"""
        try:
            # 构建数据字典（保持与原始监控相同的数据采集逻辑）
            pusher_logger.debug("系统数据推送成功")  # 调试日志
            macs = sleep_redis.get_online_devices()

            for mac in macs:
                now_data = sleep_redis.SC_GetNowTimeSleepDataByMac(mac)
                if now_data is None or len(now_data) == 0:
                    ## 不在床
                    now_data = [ datetime.now().strftime("%Y-%m-%d %H:%M:%S"),0,0,0,0,15110,1,903,0,0,0,126,87,80,83,233,13,2112,1963,5,83.000000,233.000000,83.000000,74.000000,13.000000,70.000000,0.041139,0.737342,0.055794,0.000000,13.000000,234.000000,82.000000,77.000000,-2.806644,0.467143,0.653064,0.117534,0.885223,0.043520,0.956480,1,2,3,4,5]
                socketio.emit('my_response', {'data': now_data, 'mac': mac})

        except Exception as e:
            pusher_logger.error(f"数据推送失败: {str(e)}", exc_info=True)

    def push_online_device_count(self):
        """推送当前在线设备数量"""
        try:
            # 获取在线设备列表
            online_devices = sleep_redis.get_online_devices()
            device_count = len(online_devices)
            
            # 构建推送数据
            push_data = {
                'type': 'device_count',
                'count': device_count,
                'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'devices': online_devices
            }
            
            # 通过socketio推送数据
            socketio.emit('device_count_update', push_data)
            pusher_logger.info(f"设备数量推送成功，当前在线设备数: {device_count}")
            
        except Exception as e:
            pusher_logger.error(f"设备数量推送失败: {str(e)}", exc_info=True)


# 单例模式管理
_default_pusher = None
_pusher_started = False


def get_pusher(interval=2):
    """获取推送器实例"""
    global _default_pusher
    if _default_pusher is None:
        _default_pusher = SystemPusher(interval=interval)
    return _default_pusher


def start_pushing(interval=2, scheduler=None):
    """启动推送服务"""
    global _pusher_started

    if scheduler is None:
        try:
            from utils.scheduler import get_scheduler
            scheduler = get_scheduler()
        except ImportError:
            pusher_logger.error("无法获取调度器实例")
            return None

    if _pusher_started:
        pusher_logger.warning("推送服务已在运行中")
        return get_pusher(interval)

    pusher = get_pusher(interval)
    pusher.start(scheduler)
    _pusher_started = True
    return pusher


def stop_pushing(scheduler=None):
    """停止推送服务"""
    global _default_pusher

    if scheduler is None and _default_pusher is not None:
        try:
            from utils.scheduler import get_scheduler
            scheduler = get_scheduler()
        except ImportError:
            pusher_logger.error("无法获取调度器实例")
            return

    if _default_pusher is not None:
        _default_pusher.stop(scheduler)
        globals()["_pusher_started"] = False